package com.iot.ic.common.dao;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean;

import javax.persistence.EntityManager;
import java.io.Serializable;
import java.lang.reflect.Method;

public class BaseDaoImpl implements BaseDao {

    @Autowired
    protected LocalContainerEntityManagerFactoryBean entityManagerFactory;

    protected EntityManager getEntiyManager() {
        return this.entityManagerFactory.getNativeEntityManagerFactory().createEntityManager();
    }

    @Override
    public Object addOrUpdateObject(Object o) throws Exception {
        EntityManager em = getEntiyManager();
        em.getTransaction().begin();

        try {
            Method method = o.getClass().getMethod("getId", null);
            if (method.invoke(o) == null) {
                em.persist(o);
            }
            o = em.merge(o);
            em.getTransaction().commit();

        } catch (Exception e) {
            e.printStackTrace();
            em.getTransaction().rollback();
            throw new RuntimeException(e.getMessage());
        } finally {
            em.close();
        }

        return o;
    }

    @Override
    public Object getObjectByClaz(Class clz, Serializable key) throws Exception {
        EntityManager em = getEntiyManager();

        Object o = em.find(clz, key);
        em.close();
        return o;
    }


    @Override
    public void deleObject(Object o) throws Exception {
        if (o == null) {
            return;
        }
        EntityManager em = this.getEntiyManager();
        em.getTransaction().begin();

        try {
            o = em.merge(o);
            em.remove(o);
            em.getTransaction().commit();
        } catch (Exception e) {
            e.printStackTrace();
            em.getTransaction().rollback();
            throw new RuntimeException(e.getMessage());
        } finally {
            em.close();
        }
    }
}
